package com.zscat.mallplus.service.sms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.entity.vo.sms.CouponResponse;
import com.zscat.mallplus.oms.entity.OmsCartItem;
import com.zscat.mallplus.pms.entity.PmsProduct;
import com.zscat.mallplus.pms.mapper.PmsProductMapper;
import com.zscat.mallplus.service.sms.service.ISmsCouponService;
import com.zscat.mallplus.service.ums.service.IUmsMemberService;
import com.zscat.mallplus.sms.entity.*;
import com.zscat.mallplus.sms.mapper.*;
import com.zscat.mallplus.sms.vo.SmsCouponHistoryDetail;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.util.DateUtil;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ResponseInfo;
import com.zscat.mallplus.utils.ResultResponse;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.models.auth.In;
import com.zscat.mallplus.vo.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 * 优惠卷表 服务实现类
 * </p>
 *
 * @author zscat
 * @since 2019-04-19
 */
@Service
public class SmsCouponServiceImpl extends ServiceImpl<SmsCouponMapper, SmsCoupon> implements ISmsCouponService {

    @Resource
    private SmsBargainConfigMapper bargainConfigMapper;
    @Resource
    private SmsBargainRecordMapper bargainRecordMapper;
    @Resource
    private SmsBargainMemberMapper bargainMemberMapper;

    @Resource
    private IUmsMemberService memberService;
    @Resource
    private SmsCouponMapper couponMapper;
    @Resource
    private SmsCouponHistoryMapper couponHistoryMapper;

    @Resource
    private PmsProductMapper pmsProductMapper;

    @Resource
    private SmsCouponProductCategoryRelationMapper smsCouponProductCategoryRelationMapper;

    @Resource
    private SmsCouponProductRelationMapper smsCouponProductRelationMapper;

    @Resource
    private SmsCouponStoreRelationMapper smsCouponStoreRelationMapper;

    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");


    @Override
    public List<SmsCoupon> selectNotRecive(Long memberId) {
        return couponMapper.selectNotRecive(memberId);
    }

    @Override
    public List<SmsCoupon> selectRecive(Long memberId) {
        return couponMapper.selectRecive(memberId);
    }

    @Override
    public List<SmsCoupon> selectNotRecive() {
        SmsCoupon coupon = new SmsCoupon();
        List<SmsCoupon> list = couponMapper.selectList(new QueryWrapper<>(coupon).lt("start_time", new Date()).gt("end_time", new Date()));
        return list;
    }


    public List<SmsCoupon> selectNotRecive1() {
        List<SmsCoupon> list = new ArrayList<>();
        SmsCoupon coupon = new SmsCoupon();
        try {
            UmsMember currentMember = memberService.getNewCurrentMember();
            coupon.setType(0);
            if (currentMember != null && currentMember.getId() != null) {
                List<SmsCouponHistory> histories = couponHistoryMapper.selectList(new QueryWrapper<SmsCouponHistory>().eq("member_id", currentMember.getId()));
                if (histories != null && histories.size() > 0) {
                    List<Long> ids = histories.stream()
                            .map(SmsCouponHistory::getCouponId)
                            .collect(Collectors.toList());
                    list = couponMapper.selectList(new QueryWrapper<>(coupon).lt("start_time", new Date()).gt("end_time", new Date()).notIn("id", ids));
                }

            }
        } catch (Exception e) {
            list = couponMapper.selectList(new QueryWrapper<>(coupon).lt("start_time", new Date()).gt("end_time", new Date()));

        }
        return list;

    }

    @Override
    public List<SmsCouponHistory> listMemberCoupon(Integer useStatus) {
        UmsMember currentMember = memberService.getNewCurrentMember();
        if (currentMember == null) {
            return new ArrayList<>();
        }
        if (ValidatorUtils.empty(useStatus)) {
            return couponHistoryMapper.selectList(new QueryWrapper<SmsCouponHistory>().eq("member_id", currentMember.getId()));
        }
        return couponHistoryMapper.selectList(new QueryWrapper<SmsCouponHistory>().eq("member_id", currentMember.getId()).eq("use_status", useStatus));
    }

    @Transactional
    @Override
    public CommonResult addbatch(String couponIds) {
        UmsMember currentMember = memberService.getNewCurrentMember();
        if (currentMember == null) {
            return new CommonResult().failed("优惠券不存在");
        }
        if (ValidatorUtils.empty(couponIds)) {
            return new CommonResult().failed("优惠券不存在");
        }
        String[] ids = couponIds.split(",");
        for (String couponId : ids) {
            //获取优惠券信息，判断数量
            SmsCoupon coupon = couponMapper.selectById(Long.valueOf(couponId));
            if (coupon == null) {
                return new CommonResult().failed("优惠券不存在");
            }
            if (coupon.getCount() <= 0) {
                return new CommonResult().failed("优惠券已经领完了");
            }
            Date now = new Date();
            if (now.after(coupon.getEndTime())) {
                return new CommonResult().failed("优惠券已过期");
            }
            //判断用户领取的优惠券数量是否超过限制
            SmsCouponHistory queryH = new SmsCouponHistory();
            queryH.setMemberId(currentMember.getId());
            queryH.setCouponId(Long.valueOf(couponId));

            int count = couponHistoryMapper.selectCount(new QueryWrapper<>(queryH));
            if (count >= coupon.getPerLimit()) {
                return new CommonResult().failed("您已经领取过该优惠券");
            }
            //生成领取优惠券历史
            SmsCouponHistory couponHistory = new SmsCouponHistory();
            couponHistory.setCouponId(Long.valueOf(couponId));
            couponHistory.setCouponCode(generateCouponCode(currentMember.getId()));
            couponHistory.setCreateTime(now);
            couponHistory.setMemberId(currentMember.getId());
            couponHistory.setMemberNickname(currentMember.getNickname());
            //主动领取
            couponHistory.setGetType(1);
            //未使用
            couponHistory.setUseStatus(0);
            couponHistory.setAmount(coupon.getAmount());
            couponHistory.setStartTime(coupon.getStartTime());
            couponHistory.setEndTime(coupon.getEndTime());
            couponHistory.setNote(coupon.getName() + ":满" + coupon.getMinPoint() + "减" + coupon.getAmount());
            couponHistoryMapper.insert(couponHistory);
            //修改优惠券表的数量、领取数量
            coupon.setCount(coupon.getCount() - 1);
            coupon.setReceiveCount(coupon.getReceiveCount() == null ? 1 : coupon.getReceiveCount() + 1);
            couponMapper.updateById(coupon);
        }
        return new CommonResult().success("领取成功", null);
    }

    @Transactional
    @Override
    public ResultResponse add(Long couponId) {
        UmsMember currentMember = memberService.getNewCurrentMember();
        ResultResponse resultResponse = new ResultResponse();

        ResponseInfo responseInfo = new ResponseInfo();

        if (currentMember == null) {
            resultResponse.setCode(200);
            responseInfo.setCode(500);
            responseInfo.setMsg("优惠券不存在");
            resultResponse.setData(responseInfo);

            return resultResponse;
        }
        //获取优惠券信息，判断数量
        SmsCoupon coupon = couponMapper.selectById(couponId);
        if (coupon == null) {
            resultResponse.setCode(200);
            responseInfo.setCode(500);
            responseInfo.setMsg("优惠券不存在");
            resultResponse.setData(responseInfo);
            return resultResponse;
        }
        if (coupon.getCount() <= 0) {
            resultResponse.setCode(200);
            responseInfo.setCode(501);
            responseInfo.setMsg("优惠券已经领完了");
            resultResponse.setData(responseInfo);
            return resultResponse;
        }
        Date now = new Date();
        if (now.after(coupon.getEndTime())) {
            resultResponse.setCode(200);
            responseInfo.setCode(501);
            responseInfo.setMsg("优惠券已经领完了");
            resultResponse.setData(responseInfo);
            return resultResponse;
        }
        //判断用户领取的优惠券数量是否超过限制
        SmsCouponHistory queryH = new SmsCouponHistory();
        queryH.setMemberId(currentMember.getId());
        queryH.setCouponId(couponId);

        int count = couponHistoryMapper.selectCount(new QueryWrapper<>(queryH));
        if (count >= coupon.getPerLimit()) {
            resultResponse.setCode(200);
            responseInfo.setCode(501);
            responseInfo.setMsg("优惠券已经领完了");
            resultResponse.setData(responseInfo);
            return resultResponse;
        }
        //生成领取优惠券历史
        SmsCouponHistory couponHistory = new SmsCouponHistory();
        couponHistory.setCouponId(couponId);
        couponHistory.setCouponCode(generateCouponCode(currentMember.getId()));
        couponHistory.setCreateTime(now);
        couponHistory.setMemberId(currentMember.getId());
        couponHistory.setMemberNickname(currentMember.getNickname());
        //主动领取
        couponHistory.setGetType(1);
        //未使用
        couponHistory.setUseStatus(0);
        couponHistory.setStartTime(coupon.getStartTime());
        couponHistory.setEndTime(coupon.getEndTime());
        couponHistory.setNote(coupon.getName() + ":满" + coupon.getMinPoint() + "减" + coupon.getAmount());
        couponHistory.setAmount(coupon.getAmount());

        couponHistoryMapper.insert(couponHistory);
        //修改优惠券表的数量、领取数量
        coupon.setCount(coupon.getCount() - 1);
        coupon.setReceiveCount(coupon.getReceiveCount() == null ? 1 : coupon.getReceiveCount() + 1);
        couponMapper.updateById(coupon);


        responseInfo.setCode(200);
        responseInfo.setMsg("已抢到");
        resultResponse.setData(responseInfo);
        resultResponse.setCode(200);

        return resultResponse;
    }

    /**
     * 16位优惠码生成：时间戳后8位+4位随机数+用户id后4位
     */
    private String generateCouponCode(Long memberId) {
        StringBuilder sb = new StringBuilder();
        Long currentTimeMillis = System.currentTimeMillis();
        String timeMillisStr = currentTimeMillis.toString();
        sb.append(timeMillisStr.substring(timeMillisStr.length() - 8));
        for (int i = 0; i < 4; i++) {
            sb.append(new Random().nextInt(10));
        }
        String memberIdStr = memberId.toString();
        if (memberIdStr.length() <= 4) {
            sb.append(String.format("%04d", memberId));
        } else {
            sb.append(memberIdStr.substring(memberIdStr.length() - 4));
        }
        return sb.toString();
    }

    @Override
    public List<SmsCouponHistory> list(Integer useStatus) {
        UmsMember currentMember = memberService.getNewCurrentMember();
        SmsCouponHistory couponHistory = new SmsCouponHistory();
        couponHistory.setMemberId(currentMember.getId());

        if (useStatus != null) {
            couponHistory.setUseStatus(useStatus);
        }
        return couponHistoryMapper.selectList(new QueryWrapper<>(couponHistory));
    }

    @Override
    public List<SmsCouponHistoryDetail> listCart(List<OmsCartItem> cartItemList, Integer type) {
        UmsMember currentMember = memberService.getNewCurrentMember();
        Date now = new Date();
        //获取该用户所有优惠券
        List<SmsCouponHistoryDetail> allList = couponHistoryMapper.getDetailList(currentMember.getId());
        //根据优惠券使用类型来判断优惠券是否可用
        List<SmsCouponHistoryDetail> enableList = new ArrayList<>();
        List<SmsCouponHistoryDetail> disableList = new ArrayList<>();
        for (SmsCouponHistoryDetail couponHistoryDetail : allList) {
            Integer useType = couponHistoryDetail.getCoupon().getUseType();
            BigDecimal minPoint = couponHistoryDetail.getCoupon().getMinPoint();
            couponHistoryDetail.setAmount(couponHistoryDetail.getCoupon().getAmount());
            Date endTime = couponHistoryDetail.getCoupon().getEndTime();
            if (useType.equals(0)) {
                //0->全场通用
                //判断是否满足优惠起点
                //计算购物车商品的总价
                BigDecimal totalAmount = calcTotalAmount(cartItemList);
                if (now.before(endTime) && totalAmount.subtract(minPoint).intValue() >= 0) {
                    enableList.add(couponHistoryDetail);
                } else {
                    disableList.add(couponHistoryDetail);
                }
            } else if (useType.equals(1)) {
                //1->指定分类
                //计算指定分类商品的总价
                List<Long> productCategoryIds = new ArrayList<>();
                for (SmsCouponProductCategoryRelation categoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                    productCategoryIds.add(categoryRelation.getProductCategoryId());
                }
                BigDecimal totalAmount = calcTotalAmountByproductCategoryId(cartItemList, productCategoryIds);
                if (now.before(endTime) && totalAmount.intValue() > 0 && totalAmount.subtract(minPoint).intValue() >= 0) {
                    enableList.add(couponHistoryDetail);
                } else {
                    disableList.add(couponHistoryDetail);
                }
            } else if (useType.equals(2)) {
                //2->指定商品
                //计算指定商品的总价
                List<Long> productIds = new ArrayList<>();
                for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                    productIds.add(productRelation.getProductId());
                }
                BigDecimal totalAmount = calcTotalAmountByProductId(cartItemList, productIds);
                if (now.before(endTime) && totalAmount.intValue() > 0 && totalAmount.subtract(minPoint).intValue() >= 0) {
                    enableList.add(couponHistoryDetail);
                } else {
                    disableList.add(couponHistoryDetail);
                }
            }
        }
        if (type.equals(1)) {
            return enableList;
        } else {
            return disableList;
        }
    }

    @Override
    public List<SmsCouponHistoryDetail> listCartV1(List<OmsCartItem> cartItemList, Integer type, Long memberId) {
        UmsMember currentMember = memberService.getById(memberId);
        Date now = new Date();
        //获取该用户所有优惠券
        List<SmsCouponHistoryDetail> allList = couponHistoryMapper.getDetailList(currentMember.getId());
        //根据优惠券使用类型来判断优惠券是否可用
        List<SmsCouponHistoryDetail> enableList = new ArrayList<>();
        List<SmsCouponHistoryDetail> disableList = new ArrayList<>();
        for (SmsCouponHistoryDetail couponHistoryDetail : allList) {
            Integer useType = couponHistoryDetail.getCoupon().getUseType();
            BigDecimal minPoint = couponHistoryDetail.getCoupon().getMinPoint();
            Date endTime = couponHistoryDetail.getCoupon().getEndTime();
            couponHistoryDetail.setStartTimeStr(DateUtil.dateToStr(couponHistoryDetail.getCoupon().getStartTime(), "yyyy.MM.dd"));
            couponHistoryDetail.setEndTimeStr(DateUtil.dateToStr(couponHistoryDetail.getCoupon().getEndTime(), "yyyy.MM.dd"));
            couponHistoryDetail.setAmount(couponHistoryDetail.getCoupon().getAmount());
            if (useType.equals(0)) {
                couponHistoryDetail.setUserTypeStr("全场通用");
                //0->全场通用
                //判断是否满足优惠起点
                //计算购物车商品的总价
                BigDecimal totalAmount = calcTotalAmount(cartItemList);
                if (now.before(endTime) && totalAmount.subtract(minPoint).intValue() >= 0) {
                    System.out.println("计算购物车商品的总价111");
                    enableList.add(couponHistoryDetail);
                } else {
                    System.out.println("计算购物车商品的总价222");
                    disableList.add(couponHistoryDetail);
                }
            } else if (useType.equals(1)) {
                couponHistoryDetail.setUserTypeStr("指定分类");
                //1->指定分类
                //计算指定分类商品的总价
                List<Long> productCategoryIds = new ArrayList<>();
                for (SmsCouponProductCategoryRelation categoryRelation : couponHistoryDetail.getCategoryRelationList()) {
                    productCategoryIds.add(categoryRelation.getProductCategoryId());
                }
                BigDecimal totalAmount = calcTotalAmountByproductCategoryId(cartItemList, productCategoryIds);
                if (now.before(endTime) && totalAmount.intValue() > 0 && totalAmount.subtract(minPoint).intValue() >= 0) {
                    enableList.add(couponHistoryDetail);
                } else {
                    disableList.add(couponHistoryDetail);
                }
            } else if (useType.equals(2)) {
                couponHistoryDetail.setUserTypeStr("指定商品");
                //2->指定商品
                //计算指定商品的总价
                List<Long> productIds = new ArrayList<>();
                for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                    productIds.add(productRelation.getProductId());
                }
                BigDecimal totalAmount = calcTotalAmountByProductId(cartItemList, productIds);
                if (now.before(endTime) && totalAmount.intValue() > 0 && totalAmount.subtract(minPoint).intValue() >= 0) {
                    enableList.add(couponHistoryDetail);
                } else {
                    disableList.add(couponHistoryDetail);
                }
            } else if (useType.equals(3)) {
                couponHistoryDetail.setUserTypeStr("指定店铺");
                //计算指定商品的总价
                List<Long> productIds = new ArrayList<>();
                for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
                    productIds.add(productRelation.getProductId());
                }
                BigDecimal totalAmount = calcTotalAmountByProductId(cartItemList, productIds);
                if (now.before(endTime) && totalAmount.intValue() > 0 && totalAmount.subtract(minPoint).intValue() >= 0) {
                    enableList.add(couponHistoryDetail);
                } else {
                    disableList.add(couponHistoryDetail);
                }
            }
        }
        if (type.equals(1)) {
            return enableList;
        } else {
            return disableList;
        }
    }

    private BigDecimal calcTotalAmount(List<OmsCartItem> cartItemList) {
        BigDecimal total = new BigDecimal("0");
        for (OmsCartItem item : cartItemList) {
            //  BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
            total = total.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }
        return total;
    }

    private BigDecimal calcTotalAmountByproductCategoryId(List<OmsCartItem> cartItemList, List<Long> productCategoryIds) {
        BigDecimal total = new BigDecimal("0");
        for (OmsCartItem item : cartItemList) {
            if (productCategoryIds.contains(item.getProductCategoryId())) {
                //   BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
                total = total.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
            }
        }
        return total;
    }

    private BigDecimal calcTotalAmountByProductId(List<OmsCartItem> cartItemList, List<Long> productIds) {
        BigDecimal total = new BigDecimal("0");
        for (OmsCartItem item : cartItemList) {
            if (productIds.contains(item.getProductId())) {
                //  BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
                total = total.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
            }
        }
        return total;
    }

    @Transactional
    @Override
    public void insertBarginRe(SmsBargainRecord groupRecords, SmsBargainMember query) {
        bargainRecordMapper.insert(groupRecords);
        bargainMemberMapper.insert(query);
    }

    @Override
    public PageInfo<CouponResponse> getAllCoupon(Long parentId, Long memberId, Integer pageSize, Integer pageIndex) {
        SmsCoupon coupon = new SmsCoupon();

        List<CouponResponse> result = new ArrayList<>();


        //用户已有的优惠劵
//        List<SmsCouponHistory> memberBarginRe = findMemberBarginRe("member_id", memberId);

        //List<SmsCoupon> smsCoupons = couponMapper.selectList();


        PmsProduct pmsProduct = pmsProductMapper.selectById(parentId);


        IPage<SmsCoupon> page = new Page<>();

        page.setSize(pageSize);
        page.setCurrent(pageIndex);

        IPage<SmsCoupon> smsCouponIPage = couponMapper.selectPage(page, new QueryWrapper<>(coupon).lt("start_time", new Date()).gt("end_time", new Date()));

        List<SmsCoupon> smsCoupons = smsCouponIPage.getRecords();

        for (int i = smsCoupons.size() - 1; i >= 0; i--) {
            Integer useType = smsCoupons.get(i).getUseType();

            //是指定分类使用的优惠劵
            Long couponsId = smsCoupons.get(i).getId();
            if (useType == 1) {
                //商品的分类id
                Long productCategoryId = pmsProduct.getProductCategoryId();
                SmsCouponProductCategoryRelation categoryCoupon = findCategoryCoupon("coupon_id", couponsId, "product_category_id", productCategoryId);
                if (categoryCoupon == null) {
                    smsCoupons.remove(i);
                }
            }

            //是指定商品使用的优惠劵
            if (useType == 2) {
                Long id = pmsProduct.getId();
                SmsCouponProductRelation goodsCoupon = findGoodsCoupon("coupon_id", couponsId, "product_id", id);
                if (goodsCoupon == null) {
                    smsCoupons.remove(i);
                }
            }

            //是指定店铺使用的优惠劵
            if (useType == 3) {
                Integer id = pmsProduct.getStoreId();
                SmsCouponStoreRelation storeCoupons = findStoreCoupons("coupon_id", couponsId, "store_id", id);
                if (storeCoupons == null) {
                    smsCoupons.remove(i);
                }
            }
        }


        for (SmsCoupon smsCoupon : smsCoupons) {
            CouponResponse couponResponse = new CouponResponse();
            //优惠劵id
            Long coupon_id = smsCoupon.getId();

            List<SmsCouponHistory> myCoupon = findMyCoupon("member_id", memberId, "coupon_id", coupon_id);

            //说明该优惠劵用户还未领取
            int size = myCoupon.size();
            Integer useType = smsCoupon.getUseType();
            Integer publishCount = smsCoupon.getPublishCount();

            String endTime = simpleDateFormat.format(smsCoupon.getEndTime());

            String startTime = simpleDateFormat.format(smsCoupon.getStartTime());

            //String note = smsCoupon.getName() + ":满" + smsCoupon.getMinPoint() + "减" + smsCoupon.getAmount();

            if (size == 0) {
                BeanUtils.copyProperties(smsCoupon, couponResponse);

                if (useType == 0) {
                    couponResponse.setUseType("全场可用");
                } else if (useType == 1) {
                    couponResponse.setUseType("指定分类可用");
                } else {
                    couponResponse.setUseType("指定商品可用");
                }

                //couponResponse.setNote(note);
                couponResponse.setEndTime(endTime);
                couponResponse.setStartTime(startTime);

                if (publishCount != 0) {
                    couponResponse.setCouponType(0);
                } else {
                    couponResponse.setCouponType(3);
                }
                result.add(couponResponse);
            }

            //说明优惠劵已经领取过来、需要校验是否超出最大领取数量
            if (size > 0) {
                Integer perLimit = smsCoupon.getPerLimit();
                BeanUtils.copyProperties(smsCoupon, couponResponse);

                //couponResponse.setNote(note);
                couponResponse.setEndTime(endTime);
                couponResponse.setStartTime(startTime);

                if (useType == 0) {
                    couponResponse.setUseType("全场可用");
                } else if (useType == 1) {
                    couponResponse.setUseType("指定分类可用");
                } else {
                    couponResponse.setUseType("指定商品可用");
                }

                if (publishCount != 0) {

                    if (perLimit > size) {
                        couponResponse.setCouponType(2);
                    }

                    if (perLimit == size) {
                        couponResponse.setCouponType(1);
                    }
                } else {
                    couponResponse.setCouponType(3);
                }
                result.add(couponResponse);
            }
        }
        return new PageInfo<>(pageIndex, pageSize, result);
    }

    @Override
    public PageInfo<CouponResponse> carItmsCoupon(Long memberId, Integer pageIndex, Integer pageSize) {
        List<CouponResponse> result = new ArrayList<>();
        SmsCoupon coupon = new SmsCoupon();
        IPage<SmsCoupon> page = new Page<>();

        page.setSize(pageSize);
        page.setCurrent(pageIndex);

        IPage<SmsCoupon> smsCouponIPage = couponMapper.selectPage(page, new QueryWrapper<>(coupon).lt("start_time", new Date()).gt("end_time", new Date()));

        List<SmsCoupon> smsCoupons = smsCouponIPage.getRecords();
        for (SmsCoupon smsCoupon : smsCoupons) {
            CouponResponse couponResponse = new CouponResponse();
            //优惠劵id
            Long coupon_id = smsCoupon.getId();

            List<SmsCouponHistory> myCoupon = findMyCoupon("member_id", memberId, "coupon_id", coupon_id);

            //说明该优惠劵用户还未领取
            int size = myCoupon.size();
            Integer useType = smsCoupon.getUseType();
            Integer publishCount = smsCoupon.getPublishCount();

            String endTime = simpleDateFormat.format(smsCoupon.getEndTime());

            String startTime = simpleDateFormat.format(smsCoupon.getStartTime());

            //String note = smsCoupon.getName() + ":满" + smsCoupon.getMinPoint() + "减" + smsCoupon.getAmount();

            if (size == 0) {
                BeanUtils.copyProperties(smsCoupon, couponResponse);

                if (useType == 0) {
                    couponResponse.setUseType("全场可用");
                } else if (useType == 1) {
                    couponResponse.setUseType("指定分类可用");
                } else {
                    couponResponse.setUseType("指定商品可用");
                }

                //couponResponse.setNote(note);
                couponResponse.setEndTime(endTime);
                couponResponse.setStartTime(startTime);

                if (publishCount != 0) {
                    couponResponse.setCouponType(0);
                } else {
                    couponResponse.setCouponType(3);
                }
                result.add(couponResponse);
            }

            //说明优惠劵已经领取过来、需要校验是否超出最大领取数量
            if (size > 0) {
                Integer perLimit = smsCoupon.getPerLimit();
                BeanUtils.copyProperties(smsCoupon, couponResponse);

                //couponResponse.setNote(note);
                couponResponse.setEndTime(endTime);
                couponResponse.setStartTime(startTime);

                if (useType == 0) {
                    couponResponse.setUseType("全场可用");
                } else if (useType == 1) {
                    couponResponse.setUseType("指定分类可用");
                } else {
                    couponResponse.setUseType("指定商品可用");
                }

                if (publishCount != 0) {

                    if (perLimit > size) {
                        couponResponse.setCouponType(2);
                    }

                    if (perLimit == size) {
                        couponResponse.setCouponType(1);
                    }
                } else {
                    couponResponse.setCouponType(3);
                }
                result.add(couponResponse);
            }
        }
        return new PageInfo<>(pageIndex, pageSize, result);
    }

    private SmsCouponStoreRelation findStoreCoupons(String column, Object value, String column1, Object value1) {
        QueryWrapper<SmsCouponStoreRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return smsCouponStoreRelationMapper.selectOne(queryWrapper);
    }

    private SmsCouponProductRelation findGoodsCoupon(String column, Object value, String column1, Object value1) {
        QueryWrapper<SmsCouponProductRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return smsCouponProductRelationMapper.selectOne(queryWrapper);
    }

    private SmsCouponProductCategoryRelation findCategoryCoupon(String column, Object value, String column1, Object value1) {
        QueryWrapper<SmsCouponProductCategoryRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value).eq(column1, value1);
        return smsCouponProductCategoryRelationMapper.selectOne(queryWrapper);
    }

    private List<SmsCouponHistory> findMyCoupon(String column, Object value, String column1, Object value1) {
        QueryWrapper<SmsCouponHistory> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(column, value).eq(column1, value1);

        return couponHistoryMapper.selectList(queryWrapper);
    }

    private List<SmsCouponHistory> findMemberBarginRe(String column, Object value) {
        QueryWrapper<SmsCouponHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, value);
        return couponHistoryMapper.selectList(queryWrapper);
    }
}
